<?php
/**
 * 用户管理
 *
 * $Id: class.user.php 238 2011-01-13 08:53:47Z bwanglei@gmail.com $
 */

class awUser {
	/**
	 * 内部数据对象
	 * @var MySQL
	 */
	private $db;

	function __construct() {
		$this->db = MySQL::getInstance();
	}

	/**
	 * 获取用户列表
	 *
	 * @param 用户组 $role
	 * @return array
	 */
	function getUsers($role='writer') {
		$res = $this->db->query('SELECT * FROM `'.DB_PREFIX.'users` WHERE role=\'writer\'');
		$users = array();
		while ($row = $this->db->fetch_array($res)) {
			$row['username'] = htmlspecialchars($row['username']);
			$row['nickname'] = htmlspecialchars($row['nickname']);
			$row['email'] = htmlspecialchars($row['email']);
			$users[] = $row;
		}
		return $users;
	}

	function getOneUser($uid) {
		$row = $this->db->once_fetch_array('SELECT * FROM `'.DB_PREFIX.'users` WHERE id='.$uid);
		$userData = array();
		if ($row) {
			$userData = array(
				'username' => htmlspecialchars($row['username']),
				'nickname' => htmlspecialchars($row['nickname']),
				'email' => htmlspecialchars($row['email']),
			);
		}
		return $userData;
	}

	/**
	 * 更新用户信息
	 *
	 * @param array $userData
	 * @param int $uid
	 */
	function updateUser($userData, $uid) {
		$item = array();
		foreach ($userData as $key=>$data) {
			$item[] = $key.'='.$data;
		}
		$upStr = implode(',', $item);
		$this->db->query('UPDATE `'.DB_PREFIX.'users` SET '.$upStr.' WHERE id='.$uid);
	}

	/**
	 * 添加用户
	 *
	 * @param string $username
	 * @param string $password
	 * @param string $role
	 */
	function addUser($username, $password) {
		$sql = 'INSERT INTO `'.DB_PREFIX.'users` (name,password) VALUES(\''.$username.'\',\''.$password.'\')';
		$this->db->query($sql);
	}

	/**
	 * 删除用户
	 *
	 * @param int $uid
	 */
	function deleteUser($uid) {
		$row = $this->db->once_fetch_array('SELECT id FROM `'.DB_PREFIX.'users` WHERE id<>'.$uid.' and role=\'admin\'');
		$nId = $row['id'];
		$this->db->query('UPDATE `'.DB_PREFIX.'articles` set uid='.$nid.' WHERE uid='.$uid);
		$this->db->query('DELETE FROM `'.DB_PREFIX.'users` WHERE uid='.$uid);
	}

	/**
	 * 判断用户是否存在
	 *
	 * @param string $username
	 * @rerurn boolean
	 */
	function inUserExist($username) {
		$query = $this->db->query('SELECT id FROM `'.DB_PREFIX.'users` WHERE username=\''.$username.'\'');
		$res = $this->db->num_row($query);
		if ($res > 0) {
			return true;
		} else {
			return false;
		}
	}
}
